<template>
    <div>
        <a-upload v-model:file-list="fileList" list-type="picture-card" accept="image/*" :multiple="max == 1 ? false : true"
            :disabled="disabled" :customRequest="customRequest" @preview="handlePreview" @remove="removeFile">
            <div v-if="fileList.length < max">
                <loading-outlined v-if="loading" />
                <plus-outlined v-else />
                <div class="ant-upload-text">选择图片</div>
            </div>
        </a-upload>
        <a-modal :open="previewVisible" :title="previewTitle" :footer="null" @cancel="handleCancel">
            <img alt="example" style="width: 100%" :src="previewImage" />
        </a-modal>
    </div>
</template>
<script setup lang="ts">
import { ref, computed } from 'vue';
import { message } from 'ant-design-vue';
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons-vue';
import { uploadFile } from '@/api/upload'

const props = defineProps({
    max: {
        type: Number,
        default: 1
    },
    list: {
        type: Array,
        default: ()=>[]
    },
    disabled: {
        type: Boolean,
        default: false
    },
})
const emit = defineEmits(['delete', 'upload']);
//显示的文件列表
const fileList = computed(() => {
    let list = props.list;
    let fileList: any[] = [];
    if (list && list.length) {
        list.map((item, i) => {
            fileList.push({
                uid: i,
                index:i,
                status: 'done',
                name: i + '.png',
                url: item
            })
        })
    }
    return fileList;
})
let loading = ref<boolean>(false);
//上传文件
const customRequest = async (data: any) => {
    loading.value = true;
    try {
        await dealUploadFile(data)
        message.success('上传成功')
    } finally {
        loading.value = false;
    }
}
//处理上传
const dealUploadFile = async (imgaeFile: {file: any; onProgress?: any; onSuccess?: any}) => {
    let {file} = imgaeFile
    try {
        const formData = new FormData()
        formData.append('file', file)
        let res = await uploadFile(formData)
        let { data } = res;
        emit('upload', data)
    } finally {
    }
}
//删除文件
const removeFile = (file: any) => {
    emit('delete', file)
}
//预览信息相关
const previewVisible = ref(false);
const previewImage = ref('');
const previewTitle = ref('预览信息');
//预览
const handlePreview = async (file: { url?: any; preview?: any; }) => {
    previewImage.value = file.url || file.preview;
    previewVisible.value = true;
};
//取消预览
const handleCancel = () => {
    previewVisible.value = false;
    previewImage.value = '';
};

</script>